package com.gobang.gobang;

import java.io.*;
import java.net.Socket;
import java.net.ConnectException;
import javafx.application.Platform;

public class NetworkManager {
    private Socket socket;
    private PrintWriter out;
    private BufferedReader in;
    private final String host;
    private final int port;
    private volatile boolean isRunning = true;
    
    // 添加两个控制器引用
    private RoomListController roomListController;
    private GobangController gameController;
    
    // 构造函数重载
    public NetworkManager(String host, int port, RoomListController controller) {
        this.host = host;
        this.port = port;
        this.roomListController = controller;
    }
    
    public void setGameController(GobangController controller) {
        this.gameController = controller;
    }
    
    public void connect() {
        if (socket != null && !socket.isClosed()) {
            close();
        }
        
        try {
            socket = new Socket(host, port);
            out = new PrintWriter(
                new OutputStreamWriter(socket.getOutputStream(), "UTF-8"),
                true
            );
            in = new BufferedReader(
                new InputStreamReader(socket.getInputStream(), "UTF-8")
            );
            
            // 启动接收消息的线程
            Thread receiveThread = new Thread(this::receiveMessages);
            receiveThread.setDaemon(true);
            receiveThread.start();
            
            if (roomListController != null) {
                roomListController.onConnectionSuccess();
            }
        } catch (ConnectException e) {
            if (roomListController != null) {
                roomListController.onConnectionFailed("服务器未启动");
            }
        } catch (IOException e) {
            if (roomListController != null) {
                roomListController.onConnectionFailed(e.getMessage());
            }
        }
    }
    
    private void handleConnectionError(String message) {
        if (roomListController != null) {
            roomListController.setStatusText(message);
        }
        if (gameController != null) {
            gameController.setStatusText(message);
        }
    }
    
    public void sendMessage(String message) {
        if (out != null && isRunning) {
            out.println(message);
        }
    }
    
    private void receiveMessages() {
        try {
            String message;
            while (isRunning && (message = in.readLine()) != null) {
                handleMessage(message);
            }
        } catch (IOException e) {
            if (isRunning) {
                handleConnectionError("连接断开：" + e.getMessage());
            }
        } finally {
            close();
        }
    }
    
    private void handleMessage(String message) {
        Platform.runLater(() -> {
            if (message.startsWith("ROOM_LIST|")) {
                // 房间列表消息
                String roomListData = message.substring("ROOM_LIST|".length());
                if (roomListController != null) {
                    roomListController.updateRoomList(roomListData);
                }
            } else if (message.startsWith("SCORE|")) {
                String score = message.substring("SCORE|".length());
                if (gameController != null) {
                    gameController.setScore(score);
                }
            } else if (message.equals("OPPONENT_LEFT")) {
                if (gameController != null) {
                    gameController.handleOpponentLeft();
                }
            } else if (message.startsWith("GAME_START|")) {
                // 游戏开始消息
                String color = message.substring("GAME_START|".length());
                if (gameController != null) {
                    gameController.setFirstMove("BLACK".equals(color));
                }
            } else if (message.startsWith("MOVE|")) {
                // 游戏移动消息
                String moveData = message.substring("MOVE|".length());
                if (gameController != null) {
                    gameController.handleOpponentMove(moveData);
                }
            }
        });
    }
    
    public void close() {
        isRunning = false;
        try {
            if (out != null) {
                out.close();
                out = null;
            }
            if (in != null) {
                in.close();
                in = null;
            }
            if (socket != null && !socket.isClosed()) {
                socket.close();
                socket = null;
            }
        } catch (IOException e) {
            System.err.println("Error closing connection: " + e.getMessage());
        }
    }
    
    // 添加新的构造函数
    public NetworkManager(String host, int port, GobangController controller) {
        this.host = host;
        this.port = port;
        this.gameController = controller;
    }
} 